package dryven.request;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import dryven.request.http.Request;
import dryven.request.http.Response;

public class ExceptionFrontController implements FrontController {

	private Exception _exception;
	
	
	
	public ExceptionFrontController(Exception exception) {
		super();
		_exception = exception;
	}

	@Override
	public void handleRequest(Request req, Response resp) {
		resp.setHeader("Content-Type", "text/html");
		StringBuilder _builder = new StringBuilder();
		_builder.append("<html><head><title>Dryven error: ");
		_builder.append(_exception.getMessage());
		_builder.append("</title></head><body><h1>");
		_builder.append(_exception.getMessage());
		_builder.append("</h1>");
		_builder.append(String.format("<p>An %s exception occured while initializing this application. You will have to fix this before you can run the application. Here are some clues to what happened:</p>", _exception.getClass().getName()));
		
		StringWriter sw = new StringWriter();
		PrintWriter w = new PrintWriter(sw);
		_exception.printStackTrace(w);
		_builder.append("<pre>");
		_builder.append(sw.getBuffer());
		_builder.append("</pre></body></html>");
		try {
			resp.getResponseStream().write(_builder.toString().getBytes());
		} catch (IOException e) {}
	}

	@Override
	public void shutdown() {}

}
